/**
 * @FileName: CmccOrder.java
 * @Author
 * @Description:
 * @Date 2016年1月26日 下午2:59:03
 * @CopyRight ZTE Corporation
 */
package cn.hpclub.server.model;

import java.util.Date;

import com.jfinal.ext.plugin.tablebind.TableBind;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Record;

import cn.hpclub.server.constant.Constant;

@TableBind(tableName = "cmcc_order")
public class CmccOrder extends Model<CmccOrder>{

    private static final long     serialVersionUID                 = 1312507976941244196L;

    public static final String    USERNAME                         = "username";

    public static final String    OPERATED_TIME                    = "operated_time";
    public static final String    OPERATED_DESC                    = "operated_desc";
    public static final String    ORDER_STATUS                     = "order_status";

    public static final String    ID                               = "id";
    public static final String    ORDER_ID                         = "order_id";
    public static final String    CMCC_ORDER_ID                    = "cmcc_order_id";
    public static final String    PHONE_NUMBER                     = "phone_number";
    public static final String    HANDLE_NUMBER                    = "handle_number";
    public static final String    SIM_CARD                         = "SIMCard";
    public static final String    PACKAGE_ID                       = "package_id";
    public static final String    PACKAGE_NAME                     = "package_name";
    public static final String    TARIFF_CODE                      = "tariff_code";
    public static final String    ORDER_AMOUNT                     = "order_amount";
    public static final String    PAY_AMOUNT                       = "pay_amount";
    public static final String    PAY_STATUS                       = "pay_status";
    public static final String    PAY_TIME                         = "pay_time";
    public static final String    CREATED_TIME                     = "created_time";
    public static final String    HANDLER_USER_ID                  = "handler_user_id";
    public static final String    NAME                             = "name";
    public static final String    SEX                              = "sex";
    public static final String    IDCARD                           = "IDCard";
    public static final String    Z_IMG                            = "z_img";
    public static final String    F_IMG                            = "f_img";
    public static final String    HEAD_IMG                         = "head_img";
    public static final String    NATION                           = "nation";
    public static final String    BIRTHDAY                         = "birthday";
    public static final String    ADDRESS                          = "address";
    public static final String    VISA_OFFICE                      = "visa_office";
    public static final String    EXPIRE_DATE                      = "expire_date";
    public static final String    PAY_PLAT                         = "pay_plat";

    public static final String    RAW_STR                          = "rawStr";

    public static final String    APPID                            = "appid";

    public static final String    DESC_DETAILS                     = "desc_details";      // 记录退费接口返回的数据

    public static final int       NOT_PAID                         = 1;                   // 未支付

    public static final int       PAID                             = 2;                   // 已支付

    public static final int       FAILED                           = 3;                   // 支付失败

    public static final int       REFUNDED                         = 5;                   // 退费成功

    public static final int       REFUND_FAILED                    = 6;                   // 退费失败

    public static final int       ORDER_SUBMITED                   = 0;

    public static final int       ORDER_NOT_REQUEST                = 1;                   // 尚未发起办理的订单

    public static final int       ORDER_SUC                        = 5;

    public static final int       ORDER_FAILED                     = 6;                   // 移动返回失败

    public static final int       ORDER_REQUEST_NOT_BACK           = 7;                   // 请求网络异常

    public static final int       ORDER_REQUEST_RESULT_PARSE_ERROR = 8;                   // 结果解析异常
    public static final String    TYPE                             = "type";
    public static final String    PAY_CHANNEL = "pay_channel";

    public static final CmccOrder dao                              = new CmccOrder();

    public boolean updatePayInfo(String orderId, int payStatus, Date payTime, Double payAmount){

        String sql = "update cmcc_order set pay_status=?,pay_time=?,pay_amount=? where order_id=?";

        int count = Db.update(sql, payStatus, payTime, payAmount, orderId);

        return count > 0 ? true : false;

    }

    public CmccOrder getOrderInfo(String orderId){
        String sql = "select * from cmcc_order where order_id=?";

        return dao.findFirst(sql, orderId);
    }

    public boolean updatePayStatusSuc(String orderId, int payStatus, Date time, String desc, Double amount){
        // 状态为未支付、支付失败，收到支付成功的通知，才允许更新DB并办理业务。1--未支付，3--支付失败
        String sql = "update cmcc_order set pay_status = ?,pay_time=?,operated_time=?,operated_desc=?, pay_amount=? where order_id=? and ( pay_status=1 or pay_status=3)";
        int count = Db.update(sql, payStatus, time, time, desc, amount, orderId);
        if(count >= 1){
            return true;
        }

        return false;
    }

    public boolean updatePayStatusSucV2(String orderId, int payStatus, Date time, String desc, Double amount, int orderStatus){
        // 状态为未支付、支付失败，收到支付成功的通知，才允许更新DB并办理业务。1--未支付，3--支付失败
        String sql = "update cmcc_order set pay_status = ?,pay_time=?,operated_time=?,operated_desc=?, pay_amount=? and order_status=? where order_id=? and ( pay_status=1 or pay_status=3) and order_amount=?";
        int count = Db.update(sql, payStatus, time, time, desc, amount, orderStatus, orderId, amount);
        if(count >= 1){
            return true;
        }

        return false;
    }

    public void updatePayStatusFailed(String orderId, int payStatus, Date time, String desc, Double amount){
        String sql = "update cmcc_order set pay_status = ?,pay_time=?,operated_time=?,operated_desc=?, pay_amount=? where order_id=? and pay_status="
                + NOT_PAID;

        Db.update(sql, payStatus, time, time, desc, amount, orderId);

    }

    public Record getOrder(String orderId){
        String sql = "select cc.pos_id,mo.name as username,cc.pub,co.* from cmcc_order co left join member_org mo on mo.id=co.handler_user_id left join organization o on o.id=mo.org_id left join cmcc_city city on city.group_id=(select org.NumCode from organization org where org.id=o.CityCode) left join city_counter cc on cc.cmcc_city_id=city.id where co.order_id=?";

        return Db.findFirst(sql, orderId);
    }

    public boolean exist(String orderId){
        CmccOrder order = dao.findFirst("select * from cmcc_order where order_id=?", orderId);
        if(order != null){
            return true;
        } else{
            return false;
        }

    }

    public int getUserId(String orderId){
        Record order = Db.findFirst("select handler_user_id from cmcc_order where order_id=?", orderId);
        if(order == null){
            return 0;
        }
        if(order.getInt(CmccOrder.HANDLER_USER_ID) == null){
            return 0;
        }
        return order.getInt(CmccOrder.HANDLER_USER_ID);
    }

    public String getToken(String orderId){
        Record record = Db.findFirst(
                                     "select token from user_token_map where username = (select user_name from member_org where id =(select handler_user_id from cmcc_order where order_id=?))  and is_expired=0",
                                     orderId);
        if(record == null){
            return null;
        }
        return record.getStr("token");
    }

    public boolean updateOrderStatus(String orderId, String cmccOrderId, int orderStatus, String desc, Date time,
            String sucDesc){
        String sql = "";
        int count = 0;
        if(CmccOrder.ORDER_SUC == orderStatus){
            sql = "update cmcc_order set cmcc_order_id=?,order_status=?,operated_desc=?,operated_time=?,processing_time=?,processing_desc=? where order_id=? and pay_status=2 and order_status!=5";
            count = Db.update(sql, cmccOrderId, orderStatus, desc, time, time, sucDesc, orderId);
        } else{
            sql = "update cmcc_order set cmcc_order_id=?,order_status=?,operated_desc=?,operated_time=? where order_id=? and pay_status=2 and order_status!=5";
            count = Db.update(sql, cmccOrderId, orderStatus, desc, time, orderId);
        }

        if(count > 0){
            return true;
        }
        return false;
    }

    // 操作时间为退费时间
    public boolean updateRefund(String orderId, int payStatus, String desc){
        String sql = "update cmcc_order set pay_status=?,desc_details=?,operated_time=? where order_id=?";
        int count = Db.update(sql, payStatus, desc, new Date(), orderId);
        if(count > 0){
            return true;
        }
        return false;
    }

    // 退费时间单独保存，只有退费成功才记，且，只要退费成功，则不再更新数据
    public boolean updateRefund(String orderId, int payStatus, String desc, boolean result){
        String sql = "";
        int count = 0;
        Date time = new Date();
        if(result){// 退费成功，记退费时间
            sql = "update cmcc_order set pay_status=?,desc_details=?,operated_time=?,refund_time=? where order_id=? and pay_status !="
                    + REFUNDED;
            count = Db.update(sql, payStatus, desc, time, time, orderId);
        } else{
            sql = "update cmcc_order set pay_status=?,desc_details=?,operated_time=? where order_id=? and pay_status !="
                    + REFUNDED;
            count = Db.update(sql, payStatus, desc, time, orderId);
        }
        if(count > 0){
            return true;
        }
        return false;
    }

    public CmccOrder getOrderStatusInfo(String orderId){
        String sql = "select pay_status,order_status,(case pay_status when 1 then '未支付"
                + "' when 2 then '已支付' when 3 then '支付失败" + Constant.CCB_ORDER_HINT_FOR_PAY_FAILED
                + "' when 5 then '退费成功" + Constant.CCB_ORDER_HINT_FOR_REFUNED
                + "' when 6 then '退费失败' else '出错' end)as pay_state ,(case order_status when 0 then '未知' when 1 then '未发起' when 5 then '开户成功' when 6 then '开户返回失败' when 7 then '网络异常' when 8 then '结果解析失败' else '出错' end)as order_state,operated_desc,desc_details from cmcc_order where order_id=?";

        return dao.findFirst(sql, orderId);
    }

}
